//
//  SimpleExample.swift
//  WeiBoDemo
//
//  Created by chaowen deng on 2021/3/30.
//

import SwiftUI

struct SimpleExample: View {
    
    let url: URL?
    
    @State private var data: Data?
    
    // 计算属性，只读属性
    private var image: UIImage? {
        if let data = self.data {
            return UIImage(data: data)
        }
        return nil
    }
    
    
    var body: some View {
        
        let image = self.image
        
        return Group {
            if image != nil {
                Image(uiImage: image!)
                    .resizable()
                    .scaledToFill()
            } else {
                Color.gray
            }
        }
        .frame(height: 400)
        .clipped()
        .onAppear(perform: {
            //页面即将显示时，执行耗时操作会卡顿
            if let url = self.url, self.data == nil {
                DispatchQueue.global().async {
                    //先在子线程异步执行，加载
                    let data = try? Data(contentsOf: url)
                    //执行完了，再在主线程更新UI
                    DispatchQueue.main.async {
                        self.data = data
                    }
                    
                }
                
            }
        })
        
    }
}


